package com.teatang.tadmin.core.shiro;

import com.teatang.tadmin.sysuser.mapper.SysUserMapper;
import com.teatang.tadmin.sysuser.pojo.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取当前登陆的用户信息
        Subject subject = SecurityUtils.getSubject();
        SysUser loginUser = (SysUser) subject.getPrincipal();

        // 添加权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (loginUser.getName().equals("root")) {
            info.addStringPermission("sys:index-page:index");
            info.addStringPermission("sys:index-page:welcome-1");
            info.addStringPermission("sys:menu-page:index");
            info.addStringPermission("sys:menu-page:add");
            info.addStringPermission("sys:menu-page:edit");
            info.addStringPermission("sys:menu-page:delete");
            info.addStringPermission("sys:user-page:index");
            info.addStringPermission("sys:user-page:add");
            info.addStringPermission("sys:user-page:edit");
            info.addStringPermission("sys:user-page:delete");
            info.addStringPermission("sys:role-page:index");
            info.addStringPermission("sys:role-page:add");
            info.addStringPermission("sys:role-page:edit");
            info.addStringPermission("sys:role-page:delete");
        }

        return info;
    }

    @Autowired
    private SysUserMapper sysUserMapper;

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        SysUser user = sysUserMapper.getUserByName(token.getUsername());

        if (user == null) {
            return null;
        }

        // 密码验证
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

}
